<?php

namespace addons\shopro\listener\order;

use addons\shopro\exception\Exception;
use addons\shopro\model\Cart;
use addons\shopro\model\chat\Log;
use addons\shopro\model\Config;
use addons\shopro\model\Goods;
use addons\shopro\model\Order;
use addons\shopro\model\Store;
use addons\shopro\model\User;
use addons\shopro\model\UserWalletLog;
use app\admin\model\ClinicLog;
use app\admin\model\LevelBuyLog;
use app\admin\model\UserLevelSetting;
use think\Db;

/**
 * 支付成功
 */
class Payed
{

    // 订单支付成功
    public function orderPayedAfter(&$params)
    {
        // 订单支付成功
        $order = $params['order'];

        $pay_type[0] = '';
        // 重新查询订单
        $order = Order::with('item')->where('id', $order['id'])->find();

        //查询是否有门诊店报名的订单
        if ($order['clinc_score_id'] > 0 && $order['activity_type'] == 'activity_baoming') {
            //门诊店报名购买状态修改
            ClinicLog::where(['order_sn' => $order['order_sn'], 'clinc_score_id' => $order['clinc_score_id']])->update(['is_pay' => 1]);
        }
        $items = $order ? $order['item'] : [];

        //判断会员升级专区的商品订单
        if ($order['type'] == "user_level") {
            $user = User::get($order->user_id);
            $goods = Goods::get($items[0]['goods_id']);

            $pay_type = isset($order->pay_type) &&$order->pay_type!==null ? $order->pay_type : 'wallet';
            $data = ['user_id'=>$order->user_id,'type'=>'user_level','goods'=>$goods,'pay_type'=>$pay_type];
            \think\Hook::listen('user_upgrade',$data);

//            $user_level_setting = UserLevelSetting::all();
//            $levelIds = array_column($user_level_setting, 'level', 'id');
//            $newULevelSettingAwardScore = array_column($user_level_setting, 'award_score', 'level');
//            $momArr = array_column($user_level_setting, 'mom', 'level');
//
//            $upgrade_level = $levelIds[$goods->user_level_id];
//            if($user->level+1==$upgrade_level){ //第一次购买当前等级//判断是否是复购
//                $up_user_level_setting = UserLevelSetting::where(['id' => $goods->user_level_id])->find();
//                //$user->score += $up_user_level_setting->award_score;
//                //增加会员积分
//                //User::score($up_user_level_setting->award_score, $order->user_id, 'award_score', $order->id, '会员积分商品购买', []);
//
//                $unfreeze_day = config("site.unfreeze_day");
//                $dj_score = 'level' . $upgrade_level . '_dj_score';
//                $current_level = 'level' . $user['level'] . '_dj_score';
//                $pay_type = isset($order->pay_type) &&$order->pay_type!==null ? $order->pay_type : 'wallet';
//                //增加购买记录
//                $level_buy_log = [
//                    'user_id' => $order->user_id,
//                    'level' => $upgrade_level,
//                    'money' => $goods->price,
//                    'type' => $pay_type,
//                    'ctime' => time(),
//                    'award_score' => $newULevelSettingAwardScore[$upgrade_level]
//                ];
//                $buy_log = LevelBuyLog::create($level_buy_log);
//                //购买等级奖励积分
//                User::score(bcmul($newULevelSettingAwardScore[$upgrade_level], $momArr[$upgrade_level]), $order->user_id, 'award_score', $order->id, '等级购买奖励积分', []);
//                //获取等级设置
//                $userLevelSetting = UserLevelSetting::where(['level' => $upgrade_level])->find();
//                //是否有冻结的积分
//                if ($userLevelSetting->freeze_score > 0) {
//                    //每天释放的数量
//                    $days_unfreeze = bcdiv($userLevelSetting->freeze_score, $unfreeze_day);
//                    //写冻结记录表
//                    $score_freeze_log = [
//                        'user_id' => $user->id,
//                        'unfreeze' => $userLevelSetting->freeze_score,
//                        'type' => 1,
//                        'remark' => '用户购买等级' . $userLevelSetting->level . '冻结积分',
//                        'freeze_day' => $unfreeze_day,  //冻结的天数，
//                        'released_day' => 0,
//                        'status' => 1,
//                        'ctime' => time(),
//                        'days_unfreeze' => $days_unfreeze,
//                        'source' => $buy_log->id
//                    ];
//                    Db::name('score_freeze_log')->insert($score_freeze_log);
//                    //增加用户冻结的积分
//                    Db::name('user')->where(['id' => $user->id])->setInc($dj_score, $userLevelSetting->freeze_score);
//                    $before = bcsub($user->score, $user->$current_level, 2);
//                    //购买奖励的积分后 冻结积分
//                    $user_score_log = [
//                        'user_id' => $user->id,
//                        'score' => -$userLevelSetting->freeze_score,
//                        'before' => $before,
//                        'after' => bcsub($before, $userLevelSetting->freeze_score),
//                        'memo' => '会员购买冻结等级' . $upgrade_level . '积分',
//                        'createtime' => time()
//                    ];
//                    Db::name('user_score_log')->insert($user_score_log);
//
//                    //冻结的积分是否解冻
//                    if ($userLevelSetting->unfreeze == 1) {
//                        Db::name('user')->where(['id' => $user->id])->setDec("$current_level", $user->$current_level);
//                        //增加解冻记录
//                        $user_score_log = [
//                            'user_id' => $user->id,
//                            'score' => $user->$current_level,
//                            'before' => $before,
//                            'after' => bcadd($before, $user->$current_level),
//                            'memo' => '冻结的上一级积分解冻',
//                            'createtime' => time()
//                        ];
//                        Db::name('user_score_log')->insert($user_score_log);
//                    }
//                }
//                //达到升级条件
//                $user->level += 1;
//                $user->save();
//            }
        }


        // 有门店相关的订单
        $storeIds = [];
        foreach ($items as $item) {
            if (in_array($item['dispatch_type'], ['store', 'selfetch']) && $item['store_id']) {
                $storeIds[] = $item['store_id'];
            }
        }

        $data = [];
        if ($storeIds) {
            $data = [];
            // 存在门店，查询门店管理员
            $stores = Store::with(['userStore.user'])->where('id', 'in', $storeIds)->select();
            foreach ($stores as $key => $store) {
                $userStoreList = $store['user_store'] ?: [];
                unset($store['user_store']);

                // 当前门店所有用户管理员
                $userList = [];
                foreach ($userStoreList as $user) {
                    if ($user['user']) {
                        $userList[] = $user['user'];
                    }
                }

                // 有用户才能发送消息
                if ($userList) {
                    $data[] = [
                        'store' => $store,
                        'userList' => $userList
                    ];
                }
            }
        }

        // 存在要通知的门店管理员
        if ($data) {
            // 按门店为单位发送通知
            foreach ($data as $key => $sendData) {
                \addons\shopro\library\notify\Notify::send(
                    $sendData['userList'],
                    new \addons\shopro\notifications\store\Order([
                        'store' => $sendData['store'],
                        'order' => $order,
                        'event' => 'store_order_new'
                    ])
                );
            }
        }
    }

}
